angular.module('charity.project')
    .controller('projectCtr', ['$scope', '$filter', '$projectService', '$routeParams', '$uibModal',
        function ($scope, $filter, $projectService, $routeParams,$uibModal) {
            $scope.stores = [];
            $scope.searchKeywords = '';
            $scope.filteredStores = [];
            $scope.row = '', $scope.projectType = $routeParams.type;

            $scope.select = function (page) {
                var end, start;
                start = (page - 1) * $scope.numPerPage;
                end = start + $scope.numPerPage;
                return $scope.currentPageStores = $scope.filteredStores.slice(start, end);
            };

            $scope.onFilterChange = function () {
                $scope.select(1);
                $scope.currentPage = 1;
                return $scope.row = '';
            };

            $scope.onNumPerPageChange = function () {
                $scope.select(1);
                return $scope.currentPage = 1;
            };

            $scope.onOrderChange = function () {
                $scope.select(1);
                return $scope.currentPage = 1;
            };

            $scope.search = function () {
                $projectService.list().then(function (result) {

                    $scope.stores = [];
                    result.data.forEach(function (item) {
                        if (item.level == 1){
                            $scope.stores[$scope.stores.length] = item;
                            result.data.forEach(function (child) {
                                if (child.level == 2 && child.parent == item.id){
                                    item.hasChildren = true;
                                    $scope.stores[$scope.stores.length] = child;
                                }
                            });
                        }
                    });


                    $scope.filteredStores = $filter('filter')($scope.stores, $scope.searchKeywords);
                    return $scope.onFilterChange();
                });
            };

            $scope.order = function (rowName) {
                if ($scope.row === rowName) {
                    return;
                }
                $scope.row = rowName;
                $scope.filteredStores = $filter('orderBy')($scope.stores, rowName);
                return $scope.onOrderChange();
            };
            $scope.numPerPageOpt = [3, 5, 10, 20];
            $scope.numPerPage = $scope.numPerPageOpt[2];
            $scope.currentPage = 1;
            $scope.currentPageStores = [];

            $scope.open = function(project){
                $scope.project = project;
                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'myModalContent.html',
                    controller: 'DeleteProjectCtrl',
                    resolve: {
                        project: function () {
                            return $scope.project
                        }
                    }
                });

                modalInstance.result.then(function (project) {
                    $projectService.deleteById(project.id).then(function(){
                        //刷新页面
                        $scope.search();
                    })
                }, function () {

                });
            };


            var init = function () {
                $scope.search();
                return $scope.select($scope.currentPage);
            };
            init();
        }])

    .controller('editProjectCtrl', ['$scope', '$projectService', '$routeParams', 'logger', 'cfpLoadingBar',
        function ($scope, $projectService, $routeParams, logger, cfpLoadingBar) {

            // project-tree mangement
            $scope.isPermitted = true;// verify authorization

            // content editing
            $scope.statusOptions = [{
                id: 0,
                label: '草稿'
            }, {
                id: 1,
                label: '发布'
            }];
            var parent = parseInt($routeParams.parent);
            var id = parseInt($routeParams.id);
            if (parent > 0) {  // 添加子工程
                $scope.post = {parent: parent, status: 0, level : 2};
            } else {
                //  编辑工程
                if (id > 0){
                    $projectService.getContent({
                        projectId: $routeParams.id
                    }).then(function (result) {
                        $scope.post = result.data ? result.data : {status: 0, level : 1};
                        $scope.editor = $projectService.getProjectEditor('editor-trigger');
                        $scope.editor.$txt.html($scope.post.content);
                    });
                }
                else{ // 新增父工程
                    $scope.post = {status: 0, level : 1};
                }
            }
            // 新增工程或子工程
            if ($scope.post){
                $scope.editor = $projectService.getProjectEditor('editor-trigger');
                $scope.editor.$txt.html($scope.post.content);
            }

            $scope.savePost = function () {
                if ($scope.editor){
                    $scope.post.content = $scope.editor.$txt.html();
                }
                if ($scope.post.id) {
                    console.log('update project..');
                    $projectService.update($scope.post).then(function () {
                        logger.logSuccess('保存成功');
                    }, function (error) {
                        console.log(error);
                        logger.logError('保存失败');
                    });
                } else {
                    console.log('new project..');
                    $projectService.add($scope.post).then(function (data) {
                        $scope.post.id = data.data.insertId;
                        logger.logSuccess('保存成功');
                    }, function (error) {
                        console.log(error);
                        logger.logError('保存失败');
                    });
                }

            };

            //内容图片处理
            $scope.iconFile;
            var handleIconFileSelect = function (evt) {
                var file = evt.currentTarget.files[0];
                if (file) {
                    $scope.iconFile = file;
                    var reader = new FileReader();
                    reader.onload = function (evt) {
                        $scope.$apply(function ($scope) {
                            $scope.selectIcon = evt.target.result;
                            $scope.post.cover_url = evt.target.result;
                        });
                    };
                    reader.readAsDataURL(file);
                    $scope.uploadIcon();
                }
                else {
                    $scope.$apply(function ($scope) {
                        $scope.iconFile = null;
                        $scope.selectIcon = null;
                    });

                }
            };
            angular.element(document.querySelector('#iconFileInput')).on('change', handleIconFileSelect);

            $scope.uploadIcon = function () {
                //赋值为null，使上传按钮禁用，避免多次点击
                $scope.selectIcon = null;
                cfpLoadingBar.start();
                var avFile = new AV.File($scope.iconFile.name, $scope.iconFile);
                avFile.save().then(function () {
                    console.log(avFile.url());
                    // $scope.$apply(function ($scope) {
                    //     $scope.post.cover_url = avFile.url();
                    // });
                    $scope.post.cover_url = avFile.url();
                    cfpLoadingBar.complete();
                    logger.logSuccess("上传成功");
                }, function (error) {
                    alert('上传失败:' + error.message);
                    cfpLoadingBar.complete();
                    logger.logError("上传失败");
                });
            };

        }])
    .controller('DeleteProjectCtrl', ['$scope','$projectService', '$uibModalInstance', 'project',
        function ($scope, $projectService,$uibModalInstance, project) {
            $scope.project = project;
            $scope.ok = function() {
                $uibModalInstance.close( $scope.project );
            };

            $scope.cancel = function() {
                $uibModalInstance.dismiss("cancel");
            };

        }]);